package com.xcyy.zjdxmjk.zjdxmjk.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.xcyy.zjdxmjk.zjdxmjk.VO.ResultVO;
import com.xcyy.zjdxmjk.zjdxmjk.VO.XzqVO;
import com.xcyy.zjdxmjk.zjdxmjk.common.HttpClient;
import com.xcyy.zjdxmjk.zjdxmjk.common.ResultVOUtil;
import com.xcyy.zjdxmjk.zjdxmjk.entity.*;
import com.xcyy.zjdxmjk.zjdxmjk.service.TokenService;
import com.xcyy.zjdxmjk.zjdxmjk.service.TownService;
import com.xcyy.zjdxmjk.zjdxmjk.service.UserInfoService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Console;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private TokenService tokenService;

    @GetMapping("/login")
    private String login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String code= request.getParameter("code");
        //RestTemplate
  /*      RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<AccessToken> entity=restTemplate.getForEntity("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxe7d68f45496299d7&corpsecret=EXgyTDLdr0ofBhn6vYTnFKXmFMCFk3FOmpBodFT_iDM",AccessToken.class);
        AccessToken accessToken=entity.getBody();
        log.info(accessToken.toString());
        ResponseEntity<User> entityUser=restTemplate.getForEntity("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken.getAccess_token()+"&code="+code, User.class);
        User user=entityUser.getBody();
        log.info(user.toString());
        ResponseEntity<UserInfo>  entityUserInfo=restTemplate.getForEntity("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken.getAccess_token()+"&userid="+user.getUserId(),UserInfo.class);
        UserInfo userInfo=entityUserInfo.getBody();
        log.info(userInfo.toString());
        return "dept:"+userInfo.getDepartment().toString();*/

        //hutool
       /* String accessTokenStr= HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxe7d68f45496299d7&corpsecret=EXgyTDLdr0ofBhn6vYTnFKXmFMCFk3FOmpBodFT_iDM");
        AccessToken accessToken=JSON.parseObject(accessTokenStr,AccessToken.class);
        log.info(accessTokenStr);
        String code= request.getParameter("code");
        String userStr=HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken.getAccess_token()+"&code="+code);
        log.info(userStr);
        User user=JSON.parseObject(userStr,User.class);
        String userInfoStr=HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken.getAccess_token()+"&userid="+user.getUserId());
        UserInfo userInfo=JSON.parseObject(userInfoStr,UserInfo.class);
        log.info(userInfoStr);
        return "dept:"+userInfo.getDepartment().toString();*/

        //httpclient
        UserInfo userInfo=HttpClient.login(code);
        if (userInfo==null){
           // return ResultVOUtil.error(400,"无法获取用户信息");
            return "/error.html";
        }
        log.info("-------------------------"+userInfoService.findByUserid(userInfo.getUserid()));

        if (userInfoService.findByUserid(userInfo.getUserid())==null){
            //userInfoService.sava(userInfo);
           // return ResultVOUtil.error(500,"您没有获得权限，请找管理员帮忙！");
            return "/error.html";
        }

        //获取token
        String tokenStr=null;
        TokenInfo tokenInfo=tokenService.findByUserId(userInfo.getUserid());
        if (tokenInfo==null){
            tokenInfo=new TokenInfo();
            tokenStr=createNewToken(userInfo.getUserid());
            tokenInfo.setUserId(userInfo.getUserid());
            tokenInfo.setBuildTime(String.valueOf(System.currentTimeMillis()));
            tokenInfo.setToken(tokenStr.getBytes());
            tokenService.save(tokenInfo);
        }else {
            long dbBuildTime=Long.valueOf(tokenInfo.getBuildTime());
            long currentTime=System.currentTimeMillis();
            long second= currentTime-dbBuildTime;
            if(second>0&&second<7000000){
                tokenStr=new String(tokenInfo.getToken());
            }else {
                tokenStr=createNewToken(userInfo.getUserid());
                tokenInfo.setToken(tokenStr.getBytes());
                tokenInfo.setBuildTime(String.valueOf(System.currentTimeMillis()));
                tokenService.save(tokenInfo);
            }
        }
        Cookie cookieToken=new Cookie("ZJD-Token",tokenStr);
        cookieToken.setPath("/");
        cookieToken.setMaxAge(3600);
        response.addCookie(cookieToken);
        Cookie cookieUserId=new Cookie("userid",userInfo.getUserid());
        cookieUserId.setPath("/");
        cookieUserId.setMaxAge(3600);
        response.addCookie(cookieUserId);
        return "/index.html";

    }


    private String createNewToken(String userId) {
        Date now=new Date(System.currentTimeMillis());
        Date expiration=new Date(now.getTime()+72000000);
        return Jwts
                .builder()
                .setSubject(userId)
                .setIssuedAt(now)
                .setIssuer("湖南省第一测绘院农村宅基地调查工作进展统计系统")
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256,"Alec")
                .compact();
    }

}
